package com.wordutil;

import com.wordutil.wordentity.ColumnDto;
import com.wordutil.wordentity.GenerateConfig;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author YongQiang
 * @Date 2021/4/6 15:04
 * @Version 1.0
 */
public class GenUtils {

    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("template/dto.java.vm");
        return templates;
    }

    public static void generatorCode(Table table, GenerateConfig generateParam, ZipOutputStream zip) throws Exception {
        Configuration typeConfigure = getConfig(generateParam.getTypeConfigFilePath());
        List<ColumnDto> columnDtos = new ArrayList<>();
        for (int i = generateParam.getStartRows(); i < table.numRows(); i++) {
            TableRow row = table.getRow(i);
            ColumnDto columnDto = new ColumnDto();
            columnDto.setColumnName(row.getCell(generateParam.getAttributeOffset()).text().trim());
            columnDto.setColumnComment(row.getCell(generateParam.getCommentOffset()).text().replace("\n"," ").replace(
                    "\r"," ").replace("\t"," ").trim());
            columnDto.setTypeName(generateParam.getTypeOffset() == null ? "String":
                    row.getCell(generateParam.getTypeOffset()).text().trim());
            columnDto.setTypeName(typeConfigure.getString(columnDto.getTypeName(), "String"));
            columnDtos.add(columnDto);
        }
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        Map<String, Object> map = new HashMap<>(16);
        map.put("className", generateParam.getClassName());
        map.put("comments", generateParam.getClassComment());
        map.put("columns", columnDtos);
        VelocityContext context = new VelocityContext(map);
        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, generateParam.getClassName())));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new Exception("渲染模板失败，类名：" + generateParam.getClassName(), e);
            }
        }
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig(String configureName) throws Exception {
        try {
            return new PropertiesConfiguration(configureName);
        } catch (ConfigurationException e) {
            throw new Exception("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className) {

        if (template.contains("dto.java.vm")) {
            return className + "Dto.java";
        }

        return null;
    }
}
